package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService autoScanService;
    /**
     * 添加任务到延迟队列中
     *
     * @param wmNews
     */
    @Override
    public void addWmNewsToTask(WmNews wmNews) {
        log.info("添加任务到延迟服务中----begin");
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        WmNews wmNews1 = new WmNews();
        wmNews1.setId(wmNews.getId());

        byte[] bytes = ProtostuffUtil.serialize(wmNews1);
        task.setParameters(bytes);

        scheduleClient.addTask(task);
        log.info("添加任务到延迟服务中----end");
    }

    /**
     * 消费延迟队列数据
     */
    @Override
    @Scheduled(fixedRate = 1000)
    public void scanNewsByTask() throws TesseractException, IOException {
        //1. 拉取一个人任务
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //2. 判断是否拉取到了任务
        if(null != responseResult && responseResult.getCode().equals(200) && responseResult.getData() != null){
            //3. 如果拉到了任务 则进行文章的审核
            String json_str = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(json_str, Task.class);
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            log.info("文章审核---消费任务执行---文章的id---" + wmNews.getId());
            autoScanService.autoScanWmNews(wmNews.getId());
        }

        log.info("文章审核---消费任务执行---end---");
    }
}
